package com.duolebo.uteped_sdk.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationManagerCompat;

import com.duolebo.uteped_sdk.UTEPedBleClientHelper;
import com.duolebo.uteped_sdk.db.UTEPedDb;
import com.duolebo.uteped_sdk.remind.CallRemind;
import com.duolebo.uteped_sdk.remind.CameraRemind;
import com.duolebo.uteped_sdk.remind.MusicRemind;
import com.duolebo.uteped_sdk.remind.NotificationRemind;
import com.duolebo.uteped_sdk.service.UTEPedNotificationService;

import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: LiuYang
 * @Date: 2023/12/12 14:17
 * @Description: 工具类
 */
public class Tools {

    private final static String TAG = "Tools";

    @SuppressLint("StaticFieldLeak")
    private static Context applicationContext;
    @SuppressLint("StaticFieldLeak")
    private static Activity activity;

    /**
     * application context
     *
     * @param context context
     */
    public static void setApplicationContext(Context context) {
        if (context != applicationContext) {
            applicationContext = context;
            globalInit();
        }
    }

    // 单例初始化
    private static void globalInit() {
        Log.d(TAG, "globalInit...");
        SPHelper.getDefaultInstance(applicationContext, null);
        UTEPedDb.getInstance(applicationContext);
        UTEPedBleClientHelper.getInstance(applicationContext);
        CallRemind.getInstance(applicationContext);
        CameraRemind.getInstance(applicationContext);
        MusicRemind.getInstance(applicationContext);
        NotificationRemind.getInstance(applicationContext);
        DataSyncHelper.getInstance();
        DeviceHelper.getInstance();
        BluetoothHelper.getInstance().init(applicationContext);
        Log.d(TAG, "globalInit...over");
    }

    public static void checkNotificationService() {
//        if (!isNotificationListenerEnabled(Tools.getApplicationContext())) {
//            Log.d(TAG, "Notification permission denied.");
//            return;
//        }
//
        if (isServiceRunning(UTEPedNotificationService.class.getName())) {
            Log.d(TAG, UTEPedNotificationService.class.getName() + "is already running.");
            return;
        }

        startNotificationService();
    }

    private static void startNotificationService() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                applicationContext.startForegroundService(new Intent(applicationContext, UTEPedNotificationService.class));
            }
            else {
                applicationContext.startService(new Intent(applicationContext, UTEPedNotificationService.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void stopNotificationService() {
        try {
            applicationContext.stopService(new Intent(applicationContext, UTEPedNotificationService.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void release() {
        UTEPedBleClientHelper.shareInstance().release();
    }

    public static Context getApplicationContext() {
        return applicationContext;
    }

    public static void setActivity(Activity act) {
        activity = act;
    }

    public static Activity getActivity() {
        return activity;
    }

    /**
     * 是否开启了通知权限
     * @param context context
     * @return result
     */
    public static boolean isNotificationListenerEnabled(Context context) {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(context);
        return packageNames.contains(context.getPackageName());
    }

    /**
     * 打开通知设置
     * @param context context
     */
    public static void openNotificationListenSettings(Context context) {
        try {
            Intent intent = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isNotificationEnabled(Context context) {
        boolean isOpened = false;
        try {
            isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isOpened;
    }

    public static String getSystemProperty(String propKey) {
        String propValue = null;
        try {
            Class getSysProp = Class.forName("android.os.SystemProperties");
            Method method = getSysProp.getDeclaredMethod("get", String.class);
            propValue = (String) method.invoke(null, propKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return propValue;
    }

    public static boolean isXiaoMi() {
        boolean res = false;
        String model = getSystemProperty("ro.product.odm.brand");
        if (model.equalsIgnoreCase("xiaomi")) {
            res = true;
        }
        return res;
    }

    public static boolean isGPSOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) applicationContext.getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    public static void openGPSSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            applicationContext.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean saveFile(String content, String path) {
        boolean success = false;
        try {
            FileWriter fileWriter = new FileWriter(path);
            fileWriter.write(content);
            fileWriter.close();
            success = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success;
    }

    public static void exitApp() {
        stopNotificationService();
    }

    public static boolean isServiceRunning(String className) {
        if(TextUtils.isEmpty(className)){
            return false;
        }
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) applicationContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
        if(serviceList.isEmpty()){
            return false;
        }

        for (ActivityManager.RunningServiceInfo item: serviceList) {
            if(item.service.getClassName().equals(className)){
                isRunning = true;
                break;
            }
        }

        return isRunning;
    }

    public static Map<String, Object> getAppInfo() {
        Map<String, Object> map = new HashMap<>();

        PackageManager manager = applicationContext.getPackageManager();
        PackageInfo packageInfo;
        int code = -1;
        String versionName = "";
        String appName = "";
        try {
            packageInfo = manager.getPackageInfo(applicationContext.getPackageName(), 0);
            code = packageInfo.versionCode;
            versionName = packageInfo.versionName;
            appName = applicationContext.getResources().getString(packageInfo.applicationInfo.labelRes);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        map.put("packageName", applicationContext.getPackageName());
        map.put("versionCode", code);
        map.put("versionName", versionName);
        map.put("appName", appName);

        return map;
    }
}
